package com.lanou.bookstore.user.dao;

import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

public class RegisterDao {
    public boolean register(User user) {
        Connection conn = JDBCUtil.getConn();
      String uuid=UUID.randomUUID().toString().replace("-","");
        try {

            String sqlInsert = "INSERT INTO tb_user (uid,username,password) VALUES (?,?,?)";
            PreparedStatement psInsert = conn.prepareStatement(sqlInsert);
            psInsert.setString(1,uuid);
            psInsert.setString(2,user.getUsername());
            psInsert.setString(3,user.getPassword());
            psInsert.executeUpdate();

            String getIDSql = "SELECT MAX(uid) FROM tb_user ";
            PreparedStatement psID = conn.prepareStatement(getIDSql);
            ResultSet rs = psID.executeQuery();
            rs.next();

            rs.close();
            psID.close();

            return true;

        } catch (Exception e) {
            // todo 事务关闭
            try {
                conn.rollback();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        return false;
    }

    public boolean findByUsername(String username) {
        String sql = "select count(*) from tb_user where username = ?";

        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            rs.next();
            int count = rs.getInt(1);
            ps.close();
            rs.close();
            return count > 0;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


}
